import { ChatMessageType } from "@/pages/room/components/chat/chat-message.ts";

import type HistoryUserStore from "@/pages/room/HistoryUserStore.ts";
import type { ReactiveData } from "@/pages/room/model.ts";
import type { ServerEventListener } from "@/pages/room/ws/ws.ts";

export function createUserLeaveListener(
    data: ReactiveData,
    historyUserStore: HistoryUserStore
): ServerEventListener<"user.leave"> {

    return function (details) {
        const ri = data.room;
        if (ri) {
            const index = ri.users.findIndex(user => user.id === details.user);
            if (index !== -1) {
                ri.users.splice(index, 1);
            }
        }

        data.chats.push({
            type: ChatMessageType.SYSTEM,
            metadata: {},
            content: `${historyUserStore.get(details.user)?.nickname} 离开房间`
        });
    }

}
